#include <stdio.h>
#include <stdlib.h>

typedef struct str_list
{
    struct str_list* head;
    int data;
    struct str_list* tail;
} LIST;

LIST* make_list(int data) {
    LIST* new_node = (LIST*)malloc(sizeof(LIST));
    new_node->head = NULL;
    new_node->tail = NULL;
    new_node->data = data;
    return new_node;
}

LIST* insert_list(LIST* root) {
    int data;
    LIST* new_node;
    LIST* last_node;

    data = get_data();
    new_node = make_list(data);

    if (root == NULL) {
        // this is first node!
        return new_node;
    } else {
        last_node = root;
        while(last_node->tail != NULL) {
            last_node = last_node->tail;
        }
        last_node->tail = new_node;
        new_node->head = last_node;
        return root;
    }
};

void view_all_list(LIST* root) {
    LIST* last_node;
    last_node = root;
    printf("\n");
    while(last_node->tail != NULL) {
        printf("%d -> ", last_node->data);
        last_node = last_node->tail;
    }
    printf("%d -> NULL\n\n", last_node->data);
};

void get_count_of_list(LIST* root) {
    int count = 0;
    //
    // MAKE HERE!

    LIST* last_node;
    last_node = root;
    while(last_node->tail != NULL) {
        count = count + 1;
        last_node = last_node->tail;
    }
    count = count + 1;

    //
    printf("\nlist count is %d.\n\n", count);
}

LIST* delete_list(LIST* root) {
    LIST* last_node;
    LIST* delete_node;
    last_node = root;
    while(last_node->tail != NULL) {
        last_node = last_node->tail;
    }
    if (last_node == root) {
        free(root);
        return NULL;
    } else {
        last_node = last_node->head;
        delete_node = last_node->tail;
        last_node->tail = NULL;
        free(delete_node);
        return root;
    }
};

void show_menu() {
    printf("1> 입력\n");
    printf("2> 삭제\n");
    printf("3> 보기\n");
    printf("4> 지금 갯수는?\n");
    printf("5> 종료\n");
}

int get_data() {
    int data;
    printf("데이터를 입력하시오[숫자] : ");
    scanf("%d%*c", &data);
    return data;
}

int get_menu() {
    int menu_num;
    printf("메뉴[1-4] : ");
    scanf("%d%*c", &menu_num);
    return menu_num;
}

int main()
{
    LIST* rootNode = NULL;
    int menu_num = 0;
    while(menu_num != 4) {
        show_menu();
        menu_num = get_menu();
        switch(menu_num) {
            case 1 : {
                rootNode = insert_list(rootNode);
                break;
            }
            case 2 : {
                rootNode = delete_list(rootNode);
                break;
            }
            case 3 : {
                view_all_list(rootNode);
                break;
            }
            case 4 : {
                get_count_of_list(rootNode);
                break;
            }
        }
    }
    return 0;
}
